#!/usr/bin/env python

USAGE = """

usage (run in dist folder): python Roomba/run_roomba.py [replay-settings-file]

"""
import subprocess
import sys, os
import ConfigParser
import time
import getopt

def run_episode(cf):
    pid = -1
    
    # write config to a temp file so same settings will be used as when it was started
    f = open('./Roomba/temp-settings.cfg', "w")
    cf.write(f)
    f.close()
    
    if cf.getboolean('experiment','headless'):
        modname = "Roomba"
        modpath = modname + ":common"
        pid = subprocess.Popen(['./OpenNERO',
                                    '--headless', 
                                '--modpath %s' % modpath,
                                '--mod %s' % modname])
    else:
        pid = subprocess.Popen(['./OpenNERO'])
    
    file = open("pid-file", 'w')
    file.write(str(pid.pid))
    file.close()
    
    print 'written %s to file pid-file and closed..' % str(pid.pid) 
    COUNTER_FILE = "counter" + str(pid.pid)
    
    lastNr = -2
    succes = False
    while pid.poll() == None:
        try:
            try:
                file = open(COUNTER_FILE,"r")
                number = file.read()
                file.close()
                try:
                    if number != lastNr:
                        print "Run_roomba current episode number: ", number
                        lastNr = number
                        
                    if eval(number) > cf.getint('experiment', 'episodes') :
                        print "killed after %s episodes" % number
                        succes = True
                        pid.kill()
                    elif number == "-1":
                        print "killed episode error: -1"
                        pid.kill()
                except SyntaxError: # comparing the number might give a syntax error if the file is empty
                    # while the other code is writing to it
                    pass
            except IOError:
                if lastNr != "fileExist":
                    print "file %s doesn't exist yet" % COUNTER_FILE
                    lastNr = "fileExist"
            time.sleep(0.5)
        except (KeyboardInterrupt, SystemExit):
            print 'received keyboardinterrupt/systemexit.. :/'
            pid.kill()
            print 'opennero killed? go clean and exit..'
            break
    
    print "pid.poll returns:"+str(pid.poll())+":"
    
    a = pid.wait() # probably useless now
    print '*** OpenNero ended!!'
        
    os.remove(COUNTER_FILE)
    
    if pid.poll != 0 and not(succes):
        print '*** Error: OpenNERO execution failed'
        exit(1)    


    
def main(argv):
    cf = ConfigParser.RawConfigParser()
    settingsfile = 'Roomba/settings.cfg' # modname+'os.sep'+argv[1]
    evaluate = False
    hl = 0
    if (len(sys.argv) > 1):
        evaluate = True
        hl = 1
        settingsfile = sys.argv[1]
        if len(sys.argv) > 2:
            if sys.argv[2] == '-hl':
                hl = 2
            elif sys.argv[2] == '-learn':
                hl = 2
                evaluate = False
    # if evaluating.. load different setting file
    
    if not(os.path.exists(settingsfile)):
        print 'settingsfile %s does NOT exist! (dir:%s)' % (settingsfile, os.getcwd())
        exit(1)
    
    try:
        cf.read(settingsfile)
    except Exception as e:
        print "PLEASE USE %s TO FILL OUT all the required arguments'" % settingsfile
        print e
    
    nr_experiments = cf.getint('experiment','experiments')
    
    # if evaluating.. set evaluating parameter on
    if evaluate:
        cf.set('experiment', 'evaluate','True')
        nr_experiments = 1
    if hl == 1:
        cf.set('experiment', 'headless', 'False')
    elif hl == 2:
        cf.set('experiment', 'headless', 'True')
        
    
    for i in range(0,nr_experiments):
        run_episode(cf)
        
if __name__ == "__main__":
    main(sys.argv[1:])
    
        
